//
//  AddFriendViewController.m
//  ShareNavigation
//
//  Created by 水木 傅 on 12-5-16.
//  Copyright (c) 2012年 __MyCompanyName__. All rights reserved.
//

#import "AddFriendViewController.h"
#import "ASIHTTPRequest.h"
#import "ASIFormDataRequest.h"
#import "FriendInfoCell.h"
#import "SingletonUser.h"

@implementation AddFriendViewController
@synthesize SearchFriendBar;
@synthesize searchResult;
@synthesize resultArray;
@synthesize returnFindXML;
@synthesize switchString;
@synthesize friendinfo;
@synthesize currentUserID;

-(void) viewDidLoad
{
    self.SearchFriendBar.delegate  = self;
    self.searchResult.delegate = self;
    self.searchResult.dataSource = self;
    self.resultArray = [[NSMutableArray alloc] initWithObjects: nil];
    self.friendinfo = [FriendInfo alloc];
    friendinfo.userID = @"";
    friendinfo.imageName = @"";
    currentUserID = [SingletonUser  shareManager].UserID;
}

- (void)viewDidUnload {
    [self setSearchFriendBar:nil];
    [self setSearchResult:nil];
    [self setResultArray:nil];
    [self setReturnFindXML:nil];
    [self setSwitchString:nil];
    [self setFriendinfo:nil];
    [super viewDidUnload];
}

- (IBAction)pressAddFriend:(id)sender {
    FriendInfo *info = [resultArray objectAtIndex:[sender tag]];
    NSString *message = info.userID;
    UIAlertView *alert;
    alert = [[UIAlertView alloc]
             initWithTitle:@"提示"
             message:[NSString stringWithFormat:@"确定添加\"%@\"为好友?",message]
             delegate:self
             cancelButtonTitle:@"返回"
             otherButtonTitles:@"确定",nil];
    alert.tag = [sender tag];
    [alert show];
    //NSLog(@"%d",[sender tag]);
}

-(void) getSearchFriendInfo:(NSString *)searchStr
{
    NSURL *url = [NSURL URLWithString:@"http://localhost/~walker/ShareNavigationSVN/trunk/ShareNavigationPHP/AddFriendInfo.php"];
    ASIFormDataRequest *request=[[ASIFormDataRequest alloc] initWithURL:url];
    [request setRequestMethod:@"POST"];
    [request setPostValue:searchStr forKey:@"FindUserID"];
    [request setPostValue:[self currentUserID]  forKey:@"UserID"];
    [request setDelegate:self];
    [request setDidFinishSelector:@selector(requestFindFinished:)];
    [request setDidFailSelector:@selector(requestFindFailed:)];
    [request setDefaultResponseEncoding:NSUTF8StringEncoding];
    //---  发送请求信息  ----
    [request startAsynchronous];
}

-(void) addFriendRequest:(NSString *) userID willAdddFriend:(NSString *)friendID
{
    NSURL *url = [NSURL URLWithString:@"http://localhost/~walker/ShareNavigationSVN/trunk/ShareNavigationPHP/AddFriend.php"];
    ASIFormDataRequest *request=[[ASIFormDataRequest alloc] initWithURL:url];
    [request setRequestMethod:@"POST"];
    [request setPostValue:userID forKey:@"UserID"];
    [request setPostValue:friendID forKey:@"FriendID"];
    [request setPostValue:[self stringWithUUID] forKey:@"UUID"];
    [request setDelegate:self];
    [request setDefaultResponseEncoding:NSUTF8StringEncoding];
    //---  发送请求信息  ----
    [request startSynchronous];
    NSError *error = [request error];
    NSString *message;
    NSLog(@"%@",[request responseString]);
    if (!error) 
    {
        NSString *response = [request responseString];
        if([response isEqualToString:@"TRUE"])
        {
            message = @"发送成功";
        }
        else
        {
            message = @"出现错误";
           // message = response;
        }
        UIAlertView *alert;
        alert = [[UIAlertView alloc]
                 initWithTitle:@""
                 message:message
                 delegate:nil
                 cancelButtonTitle:@"返回"
                 otherButtonTitles:nil];
        [alert show];
    }
    else
    {
        NSLog(@"进入else");
    }
    

}


//---  生成随即的uuid  ---
- (NSString*) stringWithUUID {
    CFUUIDRef    uuidObj = CFUUIDCreate(nil);//create a new UUID
    //get the string representation of the UUID
    NSString    *uuidString =(__bridge_transfer NSString *)CFUUIDCreateString(nil, uuidObj);
    CFRelease(uuidObj);
    return uuidString;
}

-(void)requestFindFinished:(ASIHTTPRequest *)request
{
    NSString *response = request.responseString;
    NSLog(@"%@",response);
    if([response isEqualToString:@"FALSE"])
    {
        UIAlertView *alert;
        alert = [[UIAlertView alloc]
                 initWithTitle:@"提醒"
                 message:@"找不到好友"
                 delegate:self
                 cancelButtonTitle:@"返回"
                 otherButtonTitles:nil];
        [alert show];
        
    }
    else
    {
        returnFindXML = response;
        [self analysisXML:returnFindXML];
    }
}

-(void)requestFindFailed:(ASIHTTPRequest *)request
{
    NSError *error = [request error];
    NSLog(@"%@",[error localizedFailureReason]);
}

#pragma ---  分析xml  ---
-(void) analysisXML:(NSString *) XMLstring
{
    NSMutableString *xmlStr = [NSMutableString stringWithString:XMLstring];
    NSData *data = [NSData dataWithBytes:[xmlStr UTF8String] length:[xmlStr lengthOfBytesUsingEncoding:NSUTF8StringEncoding]];
    
    //---  设置xml数据  ---
    NSXMLParser *parser = [[NSXMLParser alloc] initWithData:data];
    [parser setShouldProcessNamespaces:NO];
    [parser setShouldReportNamespacePrefixes:NO];
    [parser setShouldResolveExternalEntities:NO];
    [parser setDelegate: self];
    [parser parse];
}

//---  遍历xml节点  ---
-(void) parser:(NSXMLParser *)parser didStartElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName attributes:(NSDictionary *)attributeDict
{
    //NSLog(@"name.:  %@",elementName);
    switchString = elementName;
}

//---  当xml有值，则调用函数  ---
-(void)parser:(NSXMLParser *)parser foundCharacters:(NSString *)string
{
    //NSLog(@"value:   %@",string);
    //---  对每个值进行分析  ---
    if ([switchString isEqualToString:@"UserID"]) 
    {
        friendinfo.userID = string;
    }
    else if([switchString isEqualToString:@"HeadPhoto"])
    {
        friendinfo.imageName = string;
    }
        
}

//---  遇到结束标记，调用该函数  ---
-(void)parser:(NSXMLParser *)parser didEndElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName
{
    //NSLog(@"结束标记：   %@",elementName);
    if([elementName isEqualToString:@"OneFriend"])
    {
        FriendInfo *temp = [FriendInfo alloc];
        [temp SetValueFromeObject:friendinfo];
        [resultArray addObject:temp];
        friendinfo.imageName = @"";
        friendinfo.userID = @"";
    }
    
    //---  xml解析完毕  ---
    if([elementName isEqualToString:@"body"])
    {
        if([[self resultArray] count] == 0)
        {
            UIAlertView *alert;
            alert = [[UIAlertView alloc]
                     initWithTitle:@"提醒"
                     message:@"找不到好友"
                     delegate:nil
                     cancelButtonTitle:@"返回"
                     otherButtonTitles:nil];
            [alert show];
        }
        [[self searchResult]reloadData];
    }
}

//---  通过名称获取图片  ----
-(UIImage *) getPicture :(NSString *)imageName
{
    NSString *urlStr = [NSString stringWithFormat:@"http://localhost/~walker/ShareNavigationSVN/trunk/ShareNavigationPHP/upload/%@.jpg",imageName];
    NSURL *url  =[NSURL URLWithString: urlStr];
    ASIHTTPRequest *request = [ASIHTTPRequest requestWithURL:url];
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, 
                                                         NSUserDomainMask, YES);
    NSString *documentsDirectory = [paths objectAtIndex:0];
    
    NSString *archivePath = [documentsDirectory 
                             stringByAppendingPathComponent:
                             [NSString stringWithFormat:@"%@.jpg",imageName]];
    
    [request setDownloadDestinationPath:archivePath];
    return [UIImage imageWithContentsOfFile:archivePath];
}

#pragma ---  searchbardelegate  ---
- (void)searchBarTextDidEndEditing:(UISearchBar *)searchBar
{
}

- (void)searchBarSearchButtonClicked:(UISearchBar *)searchBar
{
    //NSLog(@"%@",searchBar.text);
    [[self resultArray] removeAllObjects];
    [self getSearchFriendInfo:searchBar.text];
    [[self SearchFriendBar ]resignFirstResponder];
}


#pragma ---  tableviewDatasource  ---
//---  这个是返回tablview的列数的  ---
-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 1;
}

//---  返回的是tableview的行数，一共有多少行  ---
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return [resultArray count];
}

//返回每一个对应的单元cell的东西
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    FriendInfoCell *cell = (FriendInfoCell *)[tableView dequeueReusableCellWithIdentifier:@"AddFriendInfo"];
    FriendInfo *sign = [self.resultArray objectAtIndex:indexPath.row];
    //NSLog(@"===  %@  ===",sign.imageName);
    if(![sign.imageName isEqualToString:@""])
    {
        cell.headImageView.image = [self getPicture:sign.imageName];
    }
    else
    {
        cell.headImageView.image = [UIImage imageNamed:@"null.jpg"];
    }
    cell.userIDLabel.text = sign.userID;
    cell.addButton.tag = indexPath.row;
    return cell;
}

#pragma ---  tableviewDelegate  ---
/*- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    FriendInfo *info = [resultArray objectAtIndex:indexPath.row];
    NSString *message = info.userID;
    UIAlertView *alert;
    alert = [[UIAlertView alloc]
             initWithTitle:@"警告"
             message:[NSString stringWithFormat:@"确定添加\"%@\"为好友?",message]
             delegate:self
             cancelButtonTitle:@"返回"
             otherButtonTitles:@"确定",nil];
    alert.tag = indexPath.row;
    [alert show];
}*/

#pragma ---  uiAlertViewDelegate  ---
-(void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
    if(buttonIndex == 1)
    {
        FriendInfo *info = [resultArray objectAtIndex:alertView.tag];
        //---  添加好友  ---
        NSString *friendID = info.userID;
        [self addFriendRequest:[self currentUserID] willAdddFriend:friendID];
    }
}
@end
